//
//  BRCrossingTableViewCell.m
//  百思不得姐
//
//  Created by LinBrong on 16/8/26.
//  Copyright © 2016年 LinBrong. All rights reserved.
//



#import "BRCrossingTableViewCell.h"
#import "UIImageView+WebCache.h"
#import <AVFoundation/AVFoundation.h>
#import "commentViewController.h"
#import "DSTabBarController.h"
#import "DSJinghuaNavController.h"
@interface BRCrossingTableViewCell ()
//头像
@property (weak, nonatomic) IBOutlet UIImageView *iconImageView;//
//VIp
@property (weak, nonatomic) IBOutlet UIImageView *VipImageView;//
//用户名
@property (weak, nonatomic) IBOutlet UILabel *userNameLab;//
//更新时间
@property (weak, nonatomic) IBOutlet UILabel *updateTimeLab;//
//顶部,用来作点击事件
@property (weak, nonatomic) IBOutlet UIView *topView;
//内容
@property (weak, nonatomic) IBOutlet UILabel *textLab;//
//主图
@property (weak, nonatomic) IBOutlet UIImageView *PicImageView;//
//播放次数
@property (weak, nonatomic) IBOutlet UILabel *playCountLab;//
//视频持续时长
@property (weak, nonatomic) IBOutlet UILabel *durationLab;//
//评论
@property (weak, nonatomic) IBOutlet UILabel *commentLab;
//标签
@property (weak, nonatomic) IBOutlet UILabel *tagLab;//

#pragma mark - >> 按钮相关
@property (weak, nonatomic) IBOutlet UIButton *dingBtn;
@property (weak, nonatomic) IBOutlet UIButton *caiBtn;
@property (weak, nonatomic) IBOutlet UIButton *shareBtn;
@property (weak, nonatomic) IBOutlet UIButton *commentBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *picHeight;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *musicPlayBtnCenter;

@property (weak, nonatomic) IBOutlet UIButton *playBtn;
@property (weak, nonatomic) IBOutlet UIButton *videoPlayBtn;


/*  播放器  */
@property (strong, nonatomic) AVPlayer *videoPlayer;


@end


@implementation BRCrossingTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    
    tap.numberOfTouchesRequired = 1;
    tap.numberOfTapsRequired = 1;
    
    [self.iconImageView addGestureRecognizer:tap];
    
}

#pragma mark - 点击了头像的点击事件
- (void)tapAction:(UITapGestureRecognizer *)tap
{
    NSLog(@"点击了头像");
    
    NSString *uid = self.model.u[@"uid"];
    
    if ([self.delegate respondsToSelector:@selector(loadPersonalPageDataWithUid:)]) {
        [self.delegate loadPersonalPageDataWithUid:uid];
    }
}


- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    
    // Configure the view for the selected state
}
/* 给控件赋值 */
-(void)setModel:(BRCrossingModel *)model {
    
    _model = model;
    
    
    /* 个人 u */
    NSDictionary *personDict = model.u;
    
    //头像
    [self.iconImageView sd_setImageWithURL:[NSURL URLWithString:[personDict[@"header"] lastObject]] placeholderImage:[UIImage imageNamed:@"defaultUserIcon"]];
    //发贴人昵称
    self.userNameLab.text = personDict[@"name"];
    //vip
    if(personDict[@"is_v"]){
        self.VipImageView.hidden = NO;
    }else {
        self.VipImageView.hidden = YES;
    }
    //审核通过后的建贴时间
    self.updateTimeLab.text = model.passtime;
    self.iconImageView.layer.cornerRadius = 20;
    self.iconImageView.clipsToBounds = YES;
    
    //内容
    self.textLab.text = model.text;
    
    #pragma mark - >> 音频频道赋值
    //-----根据type来返回相对应的key------
    if([model.type isEqualToString: @"audio"]){
        NSDictionary *dict = model.audio;
        //        "playfcount":1625,
        //        "download_url":Array[4],图
        //        "height":640,
        //        "width":640,
        //        "duration":533,
        //        "playcount":7958,
        //        "audio":Array[1],mp3
        //        "thumbnail":Array[2],图
        //        "thumbnail_small":Array[2]图
        //        NSInteger playcount = dict[@"playcount"];
        //        self.playCountLab.text = [NSString stringWithFormat:@"%zd次播放",playcount];
        //如果图片没有高度先不显示
        if(self.picHeight.constant > 20){
            
            NSNumber *playcount = dict[@"playcount"];
            self.playCountLab.text = [NSString stringWithFormat:@"%@次播放",playcount];
            
            self.durationLab.text = [NSString stringWithFormat:@"%d:%d",(int)dict[@"duration"]/60,(int)dict[@"duration"]%60];
            [self.PicImageView sd_setImageWithURL:[NSURL URLWithString:[dict[@"thumbnail_small"] lastObject]]];
        }
        
        CGFloat width = [dict[@"width"] floatValue];
        CGFloat heigth = [dict[@"height"] floatValue];
        NSLog(@"%lf",width);
        NSLog(@"%lf",heigth);
        if(heigth < 3000){
        self.picHeight.constant = ([UIScreen mainScreen].bounds.size.width - 32)/width * heigth ;
        }else {
            self.picHeight.constant = 3000;
        }
  
    }
    #pragma mark - >> 视频频道赋值
    else if([model.type isEqualToString: @"video"]){
        NSDictionary *dict = model.video;
        //        "playfcount":500000,
        //        "height":426,
        //        "width":240,
        //        "video":Array[2],
        //        "download":Array[2],
        //        "duration":160,
        //        "playcount":500000,
        //        "thumbnail":Array[2],
        //        "thumbnail_small":Array[2]
        
        
        //如果图片没有高度先不显示
        if(self.picHeight.constant > 20){
            //播放次数
            NSNumber *playcount = dict[@"playcount"];
            self.playCountLab.text = [NSString stringWithFormat:@"%@次播放",playcount];
            
            self.durationLab.text = [NSString stringWithFormat:@"%zd:%zd",(int)dict[@"duration"] / 60,(int)dict[@"duration"] % 60];
        }
        
        [self.PicImageView sd_setImageWithURL:[NSURL URLWithString:[dict[@"thumbnail_small"] lastObject]]];
        

        
        
        CGFloat width = [dict[@"width"] floatValue];
        CGFloat heigth = [dict[@"height"] floatValue];

        if(heigth < 3000){
            self.picHeight.constant = ([UIScreen mainScreen].bounds.size.width - 32)/width * heigth ;
        }else {
            self.picHeight.constant = 3000;
        }
    }
    #pragma mark - >> 图片频道赋值
    //如果是image
    if ([model.type isEqualToString: @"image"]){
        NSDictionary *dict = model.image;
        //        "medium":Array[1],
        //        "big":Array[3],
        //        "download_url":Array[4],
        //        "height":7310,
        //        "width":440,
        //        "small":Array[1],
        //        "thumbnail_small":Array[2]
        
        self.durationLab.text = nil;
        self.playCountLab.text = nil;
        
        NSArray *imageArr = dict[@"small"];
        
        [self.PicImageView sd_setImageWithURL:[NSURL URLWithString:imageArr.lastObject]];
        
        CGFloat width = [dict[@"width"] floatValue];
        CGFloat heigth = [dict[@"height"] floatValue];
        
        self.picHeight.constant = ([UIScreen mainScreen].bounds.size.width - 32)/width * heigth ;
        
    }
    #pragma mark - >> 文本时赋值
    //如果是文本
    if ([model.type isEqualToString: @"text"]){
        //什么都不做
        self.picHeight.constant = 0;
        self.PicImageView.image = nil;
        self.playCountLab.text = nil;
        self.durationLab.text = nil;
    }
    
    //如果是声音,显示播放声音按钮
    if([model.type isEqualToString: @"video"]){
        self.videoPlayBtn.hidden = NO;
    }else {
        self.videoPlayBtn.hidden = YES;
      
    }
    //如果是声音,显示播放声音按钮
    if([model.type isEqualToString: @"audio"]){
        self.playBtn.hidden = NO;
    }else {
        self.playBtn.hidden = YES;
    }
    
    //top_comment
    //    "voicetime":0,
    //    "precid":0,
    //    "content":"看来不光是违章这么简单吧！车上要是没什么猫腻觉不会这么干！",
    //    "like_count":1080,
    //    "u":Object{...},
    //    "preuid":0,
    //    "passtime":"2015-07-31 18:03:35",
    //    "voiceuri":"",
    //    "id":29972967
    //        model.top_comment[@"content"];
    //        model.top_comment[@"u"][@"name"];
    
    if(model.top_comment[@"u"][@"name"]&& model.top_comment[@"content"]){
        self.commentLab.text = [NSString stringWithFormat:@"%@ : %@",model.top_comment[@"u"][@"name"],model.top_comment[@"content"]];
    }
    
    //标签
    NSMutableString *tagStr = [NSMutableString string];
    [model.tags enumerateObjectsUsingBlock:^(NSDictionary * obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [tagStr appendString:[NSString stringWithFormat:@" %@",obj[@"name"]]];
    }];
    
    self.tagLab.text = tagStr.copy;
    
    //四个控钮
    [self.dingBtn setTitle:model.up forState:UIControlStateNormal];
    [self.caiBtn setTitle:[NSString stringWithFormat:@"%zd",model.down] forState:UIControlStateNormal];
    
    //    model.forward
    [self.shareBtn setTitle:[NSString stringWithFormat:@"%zd",model.forward] forState:UIControlStateNormal];
    
    if([model.comment isKindOfClass:[NSNumber class]]){
        NSLog(@"找到类型不一样 %zd",model.comment);
        //        [self.commentBtn setTitle:model.comment forState:UIControlStateNormal];
        
    }else if([model.comment isKindOfClass:[NSString class]]){
        [self.commentBtn setTitle:model.comment forState:UIControlStateNormal];
//            NSLog(@"string %@",model.comment);
    }
    
    self.dingBtn.userInteractionEnabled = YES;
    self.caiBtn.userInteractionEnabled = YES;
    self.dingBtn.selected = self.model.isSelectedUp;
    self.caiBtn.selected = self.model.isSelecteDown;
    self.videoPlayBtn.selected = self.model.videoPlay;
    self.playBtn.selected = self.model.musicPlay;
    
    if(self.model.musicPlay == YES){
        CGRect frame = self.videoPlayBtn.bounds;
        self.musicPlayBtnCenter.constant = -([UIScreen mainScreen].bounds.size.width *0.5 - frame.size.width);
    }else {
        
        self.musicPlayBtnCenter.constant = 0;
    
    }
}

#pragma mark - >> 按钮点击事件
/* 顶的点击事件 */
- (IBAction)dingAction:(UIButton *)sender {
    
    if(self.model.isSelecteDown||self.model.isSelectedUp){
    self.dingBtn.userInteractionEnabled = NO;
    self.caiBtn.userInteractionEnabled = NO;
    sender.selected =  self.model.isSelectedUp;

    }else{
        self.dingBtn.userInteractionEnabled = YES;
        self.caiBtn.userInteractionEnabled = YES;
        sender.selected = YES;
        self.model.isSelectedUp = sender.selected;
        
        //创建一点动画
        UILabel *lab = [[UILabel alloc]initWithFrame:sender.bounds];
        lab.text = @"+1";
        lab.textColor = [UIColor redColor];
        lab.textAlignment = NSTextAlignmentCenter;
        [sender addSubview:lab];
        lab.alpha = 0;

        [UIView animateWithDuration:1 animations:^{
            lab.transform = CGAffineTransformScale(lab.transform, 1.5, 1.5);
            lab.transform = CGAffineTransformTranslate(lab.transform, 20, -20);
            lab.alpha = 1;
        } completion:^(BOOL finished) {
            [lab removeFromSuperview];
        }];

    }
}
/* 踩的点击事件 */
- (IBAction)caiAction:(UIButton *)sender {
   
    if(self.model.isSelecteDown||self.model.isSelectedUp){
        
        self.dingBtn.userInteractionEnabled = NO;
        self.caiBtn.userInteractionEnabled = NO;
        sender.selected =  self.model.isSelecteDown;

    }else{
        
        self.dingBtn.userInteractionEnabled = YES;
        self.caiBtn.userInteractionEnabled = YES;
        sender.selected = YES;
        self.model.isSelecteDown = sender.selected;
        
        //创建减一点动画
        UILabel *lab = [[UILabel alloc]initWithFrame:sender.bounds];
        lab.text = @"-1";
        lab.textColor = [UIColor redColor];
        lab.textAlignment = NSTextAlignmentCenter;
        [sender addSubview:lab];
        lab.alpha = 0;
        
        [UIView animateWithDuration:1 animations:^{
            
            lab.transform = CGAffineTransformScale(lab.transform, 1.5, 1.5);
            lab.transform = CGAffineTransformTranslate(lab.transform, 20, 20);
            lab.alpha = 1;
            
        } completion:^(BOOL finished) {
            
            [lab removeFromSuperview];
            
        }];

    }

}

/* 分享的点击事件 */
- (IBAction)shareAction:(UIButton *)sender {
    
    
    
    //    _model.share_url;
}

/* 评论点击事件 */
- (IBAction)commentAction:(UIButton *)sender {
  
    commentViewController* comVc = [commentViewController commentViewController];
    
    DSTabBarController *tabVC = (DSTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    NSLog(@"%@",tabVC.childViewControllers);
    
    for (UIViewController * vc in tabVC.childViewControllers) {
        if ([vc isKindOfClass:[DSJinghuaNavController class]]) {
            DSJinghuaNavController *jinghuaVC = (DSJinghuaNavController*)vc;
            
            NSLog(@"%@",jinghuaVC);
           comVc.model = self.model;
            [jinghuaVC pushViewController:comVc animated:YES];
            
        }
    }

    
 
   

    
    
    
    //    _model.ID;//"id":"15022319"
    
}


//点击了播放
- (IBAction)playBtnAction:(UIButton *)sender {

    sender.selected = !sender.selected;
    
    self.model.musicPlay = sender.selected;
    
    if(self.model.musicPlay == YES){
        NSDictionary *dict = self.model.audio;
        NSString *urlStr = [dict[@"audio"] lastObject];
        NSLog(@"%@",urlStr);
        
        [self playWithURL:urlStr andType:@"audio"];
        
        CGRect frame = sender.bounds;
        
        
        self.musicPlayBtnCenter.constant = -([UIScreen mainScreen].bounds.size.width *0.5 - frame.size.width);
        
        
    }else {
        [self.videoPlayer pause];
        self.videoPlayer = nil;
        
        self.musicPlayBtnCenter.constant = 0;
    }
    
}

- (IBAction)videoPlayAction:(UIButton *)sender {
    
    [self.videoPlayer pause];
    self.videoPlayer = nil;
    sender.selected = !sender.selected;
    self.model.videoPlay = sender.selected;
    
    if(self.model.videoPlay == YES){
        
        NSDictionary *dict = self.model.video;
        NSString *urlStr = [dict[@"video"] lastObject];
        [self playWithURL:urlStr andType:@"video"];
    }else {
        [self.videoPlayer pause];
        self.videoPlayer = nil;
    }

    
}

- (void)playWithURL:(NSString *)strURL andType:(NSString*)type{
    
    self.videoPlayBtn.hidden = YES;
    NSURL *url = [NSURL URLWithString:strURL];
    self.videoPlayer = [[AVPlayer alloc]initWithURL:url];
    if([type isEqualToString:@"video"]){
    AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:self.videoPlayer];
        layer.frame = self.PicImageView.bounds;
    [self.PicImageView.layer addSublayer:layer];
    }
    
    [self.videoPlayer play];
    
}



@end


